package com.nintendo.utils;

import com.nintendo.pojo.netty.NettyServerNode;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

public class ZookeeperRegister {
    public static void registerNettyServer(String nodeName,String ip,Integer port) throws Exception {
        CuratorFramework zkClient = CuratorConfig.getClient();

        String path = "/"+nodeName;
        Stat stat = zkClient.checkExists().forPath(path);
        if(stat == null){
            zkClient.create().creatingParentContainersIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(path);
        }else{
            System.out.println(stat);
        }
        //创建对应的临时节点
        NettyServerNode serverNode = new NettyServerNode();
        serverNode.setIp(ip);
        serverNode.setPort(port);
        serverNode.setOnlineCounts(0);
        String nodeJson = JsonUtils.objectToJson(serverNode);
        zkClient.create().creatingParentContainersIfNeeded()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath(path+"/im-",nodeJson.getBytes());
    }
    public static String getAddressIp() throws UnknownHostException {
        InetAddress address = InetAddress.getLocalHost();
        String hostAddress = address.getHostAddress();
        System.out.println(hostAddress);
        return hostAddress;
    }

    /**
     * 增减在线人数
     * @param serverNode
     */
    public static void incrementOnLineCounts(NettyServerNode serverNode) throws Exception{
        dealOnlineCounts(serverNode,1);
    }

    /**
     * 减少在线人数
     * @param serverNode
     */
    public static void decrementOnLineCounts(NettyServerNode serverNode) throws Exception{
        dealOnlineCounts(serverNode,-1);
    }

    /**
     * 处理在线人数的增减
     * @param serverNode
     * @param counts
     */
    public static void dealOnlineCounts(NettyServerNode serverNode,Integer counts) throws Exception {
        CuratorFramework zkClient = CuratorConfig.getClient();

        InterProcessReadWriteLock readWriteLock = new InterProcessReadWriteLock(zkClient,
                "/rw-locks");
        readWriteLock.writeLock().acquire();

        try {

            String path = "/server-list";
            List<String> list = zkClient.getChildren().forPath(path);
            for (String node:list) {
                String pendingNodePath = path + "/" + node;
                System.out.println("----------------------------pendingNodePath------>"+pendingNodePath);
                String nodeValue = new String(zkClient.getData().forPath(pendingNodePath));
                NettyServerNode pendingNode = JsonUtils.jsonToPojo(nodeValue,
                        NettyServerNode.class);
                System.out.println("----------------------------pendingNode------>"+pendingNode);
                // 如果ip和端口匹配，则当前路径的节点则需要累加或者累减
                if (pendingNode.getIp().equals(serverNode.getIp()) &&
                        (pendingNode.getPort().intValue() == serverNode.getPort().intValue())) {
                    pendingNode.setOnlineCounts(pendingNode.getOnlineCounts() + counts);
                    String nodeJson = JsonUtils.objectToJson(pendingNode);
                    zkClient.setData().forPath(pendingNodePath, nodeJson.getBytes());
                }
            }

        } finally {
            readWriteLock.writeLock().release();
        }
    }

}
